#! -*- coding:utf-8 -*-
from django.core.management.base import BaseCommand

from common.cache import redis_cache
from common.level_strategy import db as level_db
from common.utils import telegram

_TG_SETTLEMENT_GROUP = -252660797

ALARM_COUNT = 30
SLEEP_TIME = 60  # 单位：分
DAILY_LIMIT_COUNT = 3

GET_MCH_NAME = {
    '6001000': 'witch',
    '6001011': 'ks',
    '6001015': 'loki',
    '6001022': 'tt',
    '6001021': 'sp',
    '6001019': 'dbl',
    '6001020': 'rm',
    '6001017': 'zs'
}


class Command(BaseCommand):
    def handle(self, **options):

        stats_dict = redis_cache.get_user_pay_count()
        user_list = [k for k, v in stats_dict.items() if int(v) >= ALARM_COUNT]
        if not user_list:
            pass
        for user in user_list:
            user = user.split(':')
            mch_id, user_id = user[0], user[1]
            if not level_db.get_mch_user_status(mch_id, user_id):
                continue
            count = redis_cache.get_user_pay_count(mch_id, user_id)

            # 加入限制名单
            redis_cache.set_recharge_risk(mch_id, user_id, SLEEP_TIME * 60)
            redis_cache.set_recharge_daily(mch_id, user_id)

            # 移除前面统计次数
            redis_cache.remove_user_pay_count(mch_id, user_id)

            tg_msg = u'产品-商户ID：%s-%s，用户ID: %s\n' % (GET_MCH_NAME.get(mch_id), mch_id, user_id)
            tg_msg += u'连续 %s 笔未支付成功，已禁止 %s 分钟内上分操作\n' % (count, SLEEP_TIME)
            telegram.send_text_msg_tele(_TG_SETTLEMENT_GROUP, tg_msg)

            recharge_daily_count = redis_cache.get_recharge_daily(mch_id, user_id)
            if int(recharge_daily_count.get('count', 0)) >= DAILY_LIMIT_COUNT \
                    and not redis_cache.get_recharge_record(mch_id, user_id):
                redis_cache.set_recharge_record(mch_id, user_id, 86400)
                tg_msg = u'产品-商户ID：%s-%s，用户ID: %s\n' % (GET_MCH_NAME.get(mch_id), mch_id, user_id)
                tg_msg += u'当日达到三次刷单条件，已禁止 24 小时内上分操作\n'
                telegram.send_text_msg_tele(_TG_SETTLEMENT_GROUP, tg_msg)
